package com.ph.clouds.tracker.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.ph.clouds.tracker.entity.TrackParamsEntity;
import com.ph.clouds.tracker.util.TrackerLog;

import java.util.ArrayList;
import java.util.concurrent.locks.ReentrantReadWriteLock;


/**
 * @Author yushuangjiang
 * @Time 2021/8/2 15:06
 * @Description： 埋点数据管理类 对外公开增删改查操作
 */

public class TrackDBManager {

    /**
     * 读写锁  多线程 支持多读单写
     */
    private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    /**
     * 新增一条数据
     */
    public static void inserTrack(Context context, TrackParamsEntity entity) {
        lock.writeLock().lock();
        ContentValues values = new ContentValues();
        values.put(DataBaseColumns.EVENTS_ID, entity.getEvent().getCaseValue());
        values.put(DataBaseColumns.PAGE_ID, entity.getPage().getCaseValue());
        values.put(DataBaseColumns.EVENTS_END_TIME, entity.getEventTime());
        SQLiteDatabase db = TrackDatabaseHelper.getInstance(context).getWritableDatabase();
        db.insert(DataBaseColumns.TABLE_NAME, null, values);
        lock.writeLock().unlock();
        db.close();
        TrackerLog.i("TrackDBManager", "新增埋点事件-" + entity.toString());
    }

    /**
     * 获取所有数据
     */
    public static ArrayList<TrackParamsEntity> getEvents(Context context) {
        lock.readLock().lock();
        ArrayList<TrackParamsEntity> messages = new ArrayList<>();
        SQLiteDatabase db = TrackDatabaseHelper.getInstance(context).getReadableDatabase();
        Cursor cursor = null;
        try {
            cursor = db.query(DataBaseColumns.TABLE_NAME, null, null, null, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                do {
                    TrackParamsEntity entity = new TrackParamsEntity();
                    entity.setPageCode(cursor.getString(cursor.getColumnIndex(DataBaseColumns.PAGE_ID)));
                    entity.setBuryingPointCode(cursor.getString(cursor.getColumnIndex(DataBaseColumns.EVENTS_ID)));
                    messages.add(entity);
                    TrackerLog.i("TrackDBManager", entity.toString());
                } while (cursor.moveToNext());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }
            db.close();
        }
        lock.readLock().unlock();
        return messages;
    }

    /**
     * 清空数据
     */
    public static void clearDbData(Context context) {
        synchronized (TrackDatabaseHelper.dbSync) {
            SQLiteDatabase db = TrackDatabaseHelper.getInstance(context).getWritableDatabase();
            db.delete(DataBaseColumns.TABLE_NAME, null, null);
        }
    }

}
